package task;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import org.eclipse.swt.graphics.ImageData;

public class ImportOracleDump extends Task {
	private ImageData imageData = null;
	@Override
	public void run(Map<String, String> props) {
		String user = props.get("user");
		String passwd = props.get("passwd");
		String tnsname = props.get("tnsname");
		String filename = props.get("file");

		try {
			
			String fromuser = getFromUser(filename);
			String command = String.format("imp.exe %s/%s@%s file=%s fromuser=%s touser=%s", user, passwd, tnsname, filename, fromuser, user);
			
			System.out.printf("%s%n", command);
			
//			Process p = Runtime.getRuntime().exec(command);
//			int exitValue = p.waitFor();
//			System.out.printf("ExitValue: %s%n", exitValue);
//			InputStream is = p.getInputStream();
//			InputStream es = p.getErrorStream();
//			boolean moreOut = true;
//			boolean moreErr = true;
//			int ch;
//			for (;;) {
//				if (moreOut) {
//					ch = is.read();
//					if (ch == -1) {
//						moreOut = false;
//					} else {
//						System.out.print((char)ch);
//					}
//				}
//				if (moreErr) {
//					ch = is.read();
//					if (ch == -1) {
//						moreErr = false;
//					} else {
//						System.err.print((char)ch);
//					}
//				}
//				if (!moreOut && !moreErr) break;
//			}
		} catch (IOException e) {
			e.printStackTrace(System.out);
//		} catch (InterruptedException e) {
//			e.printStackTrace(System.out);
		}
	}

	private String getFromUser(String filename) throws IOException {
		File file = new File(filename);
		BufferedReader is = new BufferedReader( new FileReader(file));
		is.readLine();
		String line = is.readLine();
		String fromuser = line.substring(1);
		is.close();
		return fromuser;
	}

	@Override
	public String getDescription() {
		String descr = "Import an Oracle Dump to a database.";
		return descr;
	}
	@Override
	public String[] propertyNames() {
		String[] props = { "user", "passwd", "tnsname", "file" };
		return props;
	}


	@Override
	public ImageData getImageData() {
		if (imageData == null) {
			imageData = new ImageData(this.getClass().getResourceAsStream("/img/fs_nav.png"));
		}
		return imageData;
	}


}
